package com.zzyl.nursing.service.impl;

import java.util.Collections;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.task.Content;
import com.zzyl.nursing.vo.DeviceDto;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 设备表Service业务层处理
 *
 * @author ruoyi
 * @date 2024-11-18
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;
    // 服务端请求客户端
    @Autowired
    private Client client;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询设备表
     *
     * @param id 设备表主键
     * @return 设备表
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备表列表
     *
     * @param device 设备表
     * @return 设备表
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备表
     *
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备表
     *
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备表
     *
     * @param ids 需要删除的设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备表信息
     *
     * @param id 设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 同步阿里iot平台上的所有产品
     */
    @Override
    public void syncProductList() {
        //1.查询阿里iot平台下的所有产品
        QueryProductListRequest queryProductListRequest = new QueryProductListRequest();
        queryProductListRequest.setPageSize(20);
        queryProductListRequest.setCurrentPage(1);

        //获取实例id
        queryProductListRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        // 调用第三方查询产品列表
        QueryProductListResponse queryProductListResponse = null;
        try {
            queryProductListResponse = client.queryProductList(queryProductListRequest);
        } catch (Exception e) {
            log.error("查询阿里所有iot产品失败!", e);
            throw new ServiceException("查询阿里所有iot产品失败!");
        }
        // 解析结果
        if (!queryProductListResponse.getBody().success) {
            throw new ServiceException("查询阿里所有iot产品失败!");
        }
        // 转成vo再存入redis
        List<ProductVo> productVoList = queryProductListResponse.getBody().getData().getList().getProductInfo().stream()
                .map(pro -> BeanUtil.toBeanIgnoreError(pro, ProductVo.class)).collect(Collectors.toList());
        String jsonString = JSONUtil.toJsonStr(productVoList);
        //2. 存入redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_ALL, jsonString);

    }

    /**
     * 查询所有产品
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //从redis中拿出数据
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_ALL);
        //如果数据为空返回
        if (StringUtils.isEmpty(jsonStr)) {
            return Collections.emptyList();
        }
        //解析数据返回
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void register(DeviceDto deviceDto) throws Exception {
        //1,判断设备名字是否重复
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getDeviceName, deviceDto.getDeviceName());
        long count = count(queryWrapper);
        if (count > 0) {
            throw new BaseException("设备名称已存在,请重新输入");
        }
        //2.如果否就新增设备,保存注册参数到redis中
        addIotDevice(deviceDto);

        //3.查询产品
        //从redis中取出产品的key
        String productName = getProductName(deviceDto.getProductKey());

        //4.构建设备对象
        Device device = BeanUtil.toBeanIgnoreError(deviceDto, Device.class);
        device.setProductName(productName);
        //设置位置状态 0,1,2 为床位
        if (ObjectUtil.equal(deviceDto.getLocationType(), 0)) {
            device.setPhysicalLocationType(-1);
        }
        //5.添加到设备表
        try {
            save(device);
        } catch (Exception e) {
            deleteIotDevice(deviceDto.getIotId());
            throw new RuntimeException("该老人/位置已绑定该产品，请重新选择");
        }


    }

    /**
     * 删除旧的设备数据
     *
     * @param iotId
     */
    private void deleteIotDevice(String iotId) {
        DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
        deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        deleteDeviceRequest.setIotId(iotId);
        try {
            client.deleteDevice(deleteDeviceRequest);
        } catch (Exception e) {
            log.error("新增设备失败,删除iot设备失败:{}", iotId, e);
            throw new ServiceException("新增设备失败,删除iot设备失败");
        }
    }

    /**
     * 查询设备详细数据
     */
    @Override
    public DeviceVo queryDeviceDetail(DeviceDto deviceDto) {
        DeviceVo vo = queryDeviceDetailsFromIot(deviceDto.getIotId());
        //2. 查询数据库中的设备信息
        Device device = lambdaQuery().eq(Device::getIotId, deviceDto.getIotId()).one();
        //3. 组合返回, CopyOptions: 复制属性，忽略null值
        BeanUtil.copyProperties(device, vo, CopyOptions.create().ignoreNullValue());
        return vo;
    }

    /**
     * 查询云平台上的设备信息
     *
     * @param iotId
     * @return
     */
    private DeviceVo queryDeviceDetailsFromIot(String iotId) {
        QueryDeviceDetailRequest queryDeviceDetailRequest = new QueryDeviceDetailRequest();
        queryDeviceDetailRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        queryDeviceDetailRequest.setIotId(iotId);

        try {
            QueryDeviceDetailResponse res = client.queryDeviceDetail(queryDeviceDetailRequest);
            if (res.getBody().success) {
                return BeanUtil.toBeanIgnoreError(res.getBody().getData(), DeviceVo.class);
            }
        } catch (Exception e) {
            log.error("查询设备详情失败! {}", iotId, e);
        }
        throw new ServiceException("查询Iot设备详情失败");
    }

    /**
     * 查询产品的名称(redis)
     *
     * @param productKey
     * @return
     */
    private String getProductName(String productKey) {
        String jsonString = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_ALL);
        // 转成javaList集合
        List<ProductVo> productVoList = JSONUtil.toList(jsonString, ProductVo.class);
        return productVoList.stream().filter(productVo -> productKey.equals(productVo.getProductKey()))
                .findFirst()
                .orElseThrow(() -> new ServiceException("没有对应的产品信息!"))
                .getProductName();

    }

    /**
     * 注册Iot设备，返回新增设备的iotId
     *
     * @param
     */
    private void addIotDevice(DeviceDto dto) {
        try {
            RegisterDeviceRequest request = dto.getRegisterDeviceRequest();
            request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
            request.setProductKey(dto.getProductKey());
            RegisterDeviceResponse res = client.registerDevice(request);
            if (res.getBody().success) {
                dto.setIotId(res.getBody().getData().getIotId());
                return;
            }
        } catch (Exception e) {
            log.error("注册设备失败!", e);
        }
        throw new ServiceException("注册设备失败!");
    }

    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     */
    @Override
    public AjaxResult queryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryThingModelPublishedResponse response;
        try {
            response = client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口查询物模型失败");
        }
        if (!response.getBody().success) {
            throw new BaseException(response.getBody().getErrorMessage());
        }
        return AjaxResult.success(response.getBody().getData());
    }

    /**
     * 查询指定设备的物模型运行状态
     *
     * @param request
     * @return
     */
    @Override
    public AjaxResult QueryDevicePropertyStatusRequest(QueryDevicePropertyStatusRequest request) {
        //获取云平台上的实例id
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        QueryDevicePropertyStatusResponse response;

        //查询设备属性的状态
        try {
            response = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备属性状态，调用失败");
        }
        if (!response.getBody().success) {
            throw new BaseException(response.getBody().getErrorMessage());
        }
        // 封装数据返回
        return AjaxResult.success(response.getBody().getData());
    }

    /**
     * 删除设备
     * @param deleteDeviceRequest
     */
    @Override
    public void deleteDeviceRequest(DeleteDeviceRequest deleteDeviceRequest) {
        deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        deleteDeviceRequest.setIotId(deleteDeviceRequest.getIotId());
        deleteDeviceRequest.setProductKey(deleteDeviceRequest.getProductKey());
        deviceMapper.deleteById(deleteDeviceRequest.iotId);

    }
}



